//
//  LLPlayerContainerView.m
//  VideoPlayerProject
//
//  Created by admin on 2019/11/22.
//  Copyright © 2019 admin. All rights reserved.
//

#import "LLPlayerContainerView.h"
#import "LLNotifyCenter.h"
#import "LLProgressSetView.h"
#import <MediaPlayer/MediaPlayer.h>

typedef enum : NSUInteger {
    PanGestureSetVideoUnknown,
    PanGestureSetVideoTime,     // 设置时间
    PanGestureSetVideoVolume,   // 设置音量
    PanGestureSetVideoLight,    // 设置亮度
} PanGestureSetVideoType;

#define kTopOperationViewH 40
#define kCommonViewH 30
#define kBottomOprationViewH 40
#define kTimeLabelW 60
#define kMargin 5
#define kTimerDuration 5

@interface LLPlayerContainerView ()
{
    CGFloat _statusBarH;
}
@property (nonatomic, assign) CGRect originFrame;    // 初始化时的frame
@property (nonatomic, strong) AVPlayerLayer *playerLayer;   // 播放器layer
@property (nonatomic, weak) UIView *mySuperView;  // 自己的父视图
@property (nonatomic, weak) UIViewController *viewController;
@property (nonatomic, strong) UIPanGestureRecognizer *moviePan;
@property (nonatomic, strong) AVPlayer *avPlayer;
@property (nonatomic , assign) CGFloat totalTime;  //视频总长度(单位秒)
@property (nonatomic, assign) BOOL isDragingSlider; // 是否正在拖动滑动
@property (nonatomic, assign) BOOL topAndBottomHidden;    // 是否隐藏了上下操作视图
@property (nonatomic, assign) NSInteger currentPlaySecondTime;  // 当前播放到了多少秒
@property (nonatomic, strong) LLProgressSetView *progressSetView;   // 设置进度
@property (nonatomic, strong) UIProgressView *bottomProgressView;   // 最下面的进度条
@property (nonatomic, strong) UIActivityIndicatorView *activityView;    // 菊花

@property (nonatomic , strong) UISlider *volumeViewSlider;  /// 音量
@property (nonatomic, assign) CGFloat endVolume;       // 手势滑动结束时的音量
@property (nonatomic, strong) MPVolumeView *volumeView;

@property (nonatomic, assign) PanGestureSetVideoType setVideoType;
@property (nonatomic, assign) CGFloat screenLight;      // 屏幕亮度
@property (nonatomic, assign) CGFloat endLight;         // 手势滑动结束时的亮度

@property (nonatomic, strong) UIImageView *volumeOrLightImageView;      // 声音或亮度的图标
@property (nonatomic, strong) UIProgressView *volumeOrLightProgressView;    // 声音或亮度的进度

@property (nonatomic, strong) UIImage *muteImage;   // 静音image
@property (nonatomic, strong) UIImage *volumeImage;   // 有声音的image

@property (nonatomic, assign) CGFloat originalBrightness;   // 系统原始亮度
@property (nonatomic, assign) CGFloat originalVolume;   // 系统原始音量大小
///需要移除观察者吗
@property (nonatomic, assign) BOOL needRemoveObserver;

@end

@implementation LLPlayerContainerView

- (instancetype)initWithFrame:(CGRect)frame superView:(nonnull UIView *)superView inViewController:(nonnull UIViewController *)viewController
{
    self = [super initWithFrame:frame];
    if (self) {
        
        ///状态栏高度
        getStatusBarHeight(_statusBarH);
        
        self.backgroundColor = [UIColor blackColor];
        self.mySuperView = superView;
        self.originFrame = frame;
        self.viewController = viewController;
        
        self.muteImage = [UIImage imageNamed:@"ll_volume_close"];
        self.volumeImage = [UIImage imageNamed:@"ll_volume"];
        
        // 添加通知
        [self addNotifyCenter];
        
        [self autoHiddenOperationView];
        
        // 调节系统音量
        self.originalVolume = [AVAudioSession sharedInstance].outputVolume;
        self.originalBrightness = [UIScreen mainScreen].brightness;
        
        self.endLight = self.originalBrightness;
        self.endVolume = self.originalVolume;
        
        //单击手势
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        [self addGestureRecognizer:tap];
        
        // 处理屏幕旋转
        [self handleScreenRotation];
        
        
//        @weakify(self)
//        [self.viewController aspect_hookSelector:@selector(viewDidDisappear:) withOptions:AspectPositionAfter usingBlock:^(id<AspectInfo> info, BOOL animatin) {
//            @strongify(self)
//            [[LLNotifyCenter shareCenter] removeObserver:self];
//            [self.avPlayer.currentItem removeObserver:self forKeyPath:@"status"];
//            [self.avPlayer.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
//            [self restoreSystemValue];
//        } error:nil];
        
        
        [self setVolumeOrLightViewHidden:YES];
        [superView addSubview:self];
        
        

        
        
    }
    return self;
}

- (void)pause
{
    [self.avPlayer pause];
}

- (void)play
{
    [self.avPlayer play];
}


- (void)tapAction:(UITapGestureRecognizer *)tap
{
    [self cancelAutoHiddenOperationView];
    if (self.topAndBottomHidden) {
        // 显示上下视图
        [self showOperationView];
        [self autoHiddenOperationView];
    } else {
        // 隐藏上下视图
        [self hiddenOperationView];
    }
}

- (void)moviePanAction:(UIPanGestureRecognizer *)pan
{
    // 获取手势位置
    CGPoint locationPoint = [pan locationInView:self];
    NSLog(@">>>> loc == %@", NSStringFromCGPoint(locationPoint));
    // 获取手势速度
    CGPoint speed = [pan velocityInView:self];
    if (pan.state == UIGestureRecognizerStateBegan) {
        if (ABS(speed.x) > ABS(speed.y)) {
            // 调节快进快退
            self.progressSetView.hidden = NO;
            self.isDragingSlider = YES;
            [self cancelAutoHiddenOperationView];   ///取消自动隐藏
            self.playButton.hidden = YES;
            
            self.setVideoType = PanGestureSetVideoTime;
            
            [self setVolumeOrLightViewHidden:YES];
            
        } else {
            [self setVolumeOrLightViewHidden:NO];
            [self hiddenOperationView];
            if (locationPoint.x > self.bounds.size.width / 2) {
                // 调节音量
                self.volumeOrLightImageView.image = self.endVolume == 0 ? self.muteImage : self.volumeImage;
                self.setVideoType = PanGestureSetVideoVolume;
                self.volumeOrLightProgressView.progress = self.endVolume;
            }else {
                // 调节亮度
                self.volumeOrLightImageView.image = [UIImage imageNamed:@"ll_light"];
                self.setVideoType = PanGestureSetVideoLight;
                self.volumeOrLightProgressView.progress = self.endLight;
            }
        }
    }
    
    switch (self.setVideoType) {
        case PanGestureSetVideoTime:
            [self setVideoTimeWithGestureRecognizer:pan];
            break;
        case PanGestureSetVideoVolume:
            [self setVideoVolumeWithGestureRecognizer:pan];
            break;
        case PanGestureSetVideoLight:
        [self setVideoLightWithGestureRecognizer:pan];
        break;
        
        default:
            break;
    }
    
    

}

///退出播放时恢复系统原始值
- (void)restoreSystemValue
{
    self.volumeViewSlider.value = self.originalVolume;
    [UIScreen mainScreen].brightness = self.originalBrightness;
}

- (void)setVolumeOrLightViewHidden:(BOOL)hidden
{
    self.volumeOrLightImageView.hidden = hidden;
    self.volumeOrLightProgressView.hidden = hidden;
}

///调节视频亮度
- (void)setVideoLightWithGestureRecognizer:(UIPanGestureRecognizer *)pan
{
    // x > 0：向右滑，x < 0：向左滑；y > 0：向下滑，y < 0：向上滑
    CGPoint point = [pan translationInView:pan.view];
    CGFloat light = -point.y / self.frame.size.height + self.endLight;
    light = light > 1 ? 1 : (light < 0 ? 0 : light);
    [UIScreen mainScreen].brightness = light;
    
    self.volumeOrLightProgressView.progress = light;
    
    if (pan.state == UIGestureRecognizerStateEnded) {
        self.endLight = light;
        [self setVolumeOrLightViewHidden:YES];
    }
}

///调节视频音量
- (void)setVideoVolumeWithGestureRecognizer:(UIPanGestureRecognizer *)pan
{
    // x > 0：向右滑，x < 0：向左滑；y > 0：向下滑，y < 0：向上滑
    CGPoint point = [pan translationInView:pan.view];
    
    CGFloat volume = -point.y / self.frame.size.height + self.endVolume;
    volume = volume > 1 ? 1 : (volume < 0 ? 0 : volume);
    [self.volumeViewSlider setValue:volume];
    [self.volumeViewSlider sendActionsForControlEvents:UIControlEventTouchUpInside];
//    NSLog(@"--> %f", volume);
    self.volumeOrLightProgressView.progress = volume;
    
    self.volumeOrLightImageView.image = volume == 0 ? self.muteImage : self.volumeImage;
    
    if (pan.state == UIGestureRecognizerStateEnded) {
        self.endVolume = self.volumeViewSlider.value;
        [self setVolumeOrLightViewHidden:YES];
    }
}

// 手势滑动调节视频进度
- (void)setVideoTimeWithGestureRecognizer:(UIPanGestureRecognizer *)pan
{
    // x > 0：向右滑，x < 0：向左滑；y > 0：向下滑，y < 0：向上滑
    CGPoint point = [pan translationInView:pan.view];
    
    NSInteger slideTime = (NSInteger)(point.x * self.totalTime / self.frame.size.width);
    //滑动结束，跳转播放
    NSInteger second = self.currentPlaySecondTime + slideTime;
    if (second < 0) {
        second = 0;
    } else if (second > self.totalTime) {
        second = self.totalTime;
    }

    self.progressSetView.currentSecond = second;
    //设置滑块进度
    CGFloat slideValue = second / self.totalTime;
    [self.progressSlider setValue:slideValue animated:NO];
    //设置当前播放时间
    [self setTimeLabelTextWithLabel:self.playTimeLabel CurrentOrTotalTime:second];
    //最下面的进度条
    self.bottomProgressView.progress = slideValue;

    if (pan.state == UIGestureRecognizerStateEnded) {
        
        self.isDragingSlider = NO;
        self.progressSetView.hidden = YES;
        self.playButton.hidden = NO;
        
        [self.activityView startAnimating];
        // 跳转播放
        [self.avPlayer seekToTime:CMTimeMake(second, 1)];
        [self autoHiddenOperationView];  //添加自动隐藏
    }
}

- (void)setVideoUrlString:(NSString *)videoUrlString
{
    _videoUrlString = [videoUrlString stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    NSURL *url = [NSURL URLWithString:_videoUrlString];
    if (url.host && url.scheme && url.path) {
        AVAsset *asset = [AVAsset assetWithURL:url];
        AVPlayerItem *item = [AVPlayerItem playerItemWithAsset:asset];
        self.avPlayer = [AVPlayer playerWithPlayerItem:item];
        
        self.playerLayer.player = self.avPlayer;
        
        [self.avPlayer play];
        self.playButton.selected = NO;
        // 添加观察者
        [self configObserver];
        
        [self.activityView startAnimating];
    } else {
        [MBProgressHUD showError:@"无效地址"];
    }
    
}

//添加通知
- (void)addNotifyCenter
{
    @weakify(self)
    // 时间跳转的通知，到这里可以隐藏 加载动画，开始播放了
    [[LLNotifyCenter shareCenter] addObserver:self name:AVPlayerItemTimeJumpedNotification object:nil usingBlock:^(NSNotification * _Nullable notify) {
        @strongify(self)
        [self.activityView stopAnimating];
    }];
    //播放结束
    [[LLNotifyCenter shareCenter] addObserver:self name:AVPlayerItemDidPlayToEndTimeNotification object:nil usingBlock:^(NSNotification * _Nullable notify) {
        @strongify(self)
        /// 从头播放，循环播放
        @weakify(self)
        [self.avPlayer seekToTime:CMTimeMake(0, 1) completionHandler:^(BOOL finished) {
            @strongify(self)
            [self.avPlayer pause];
            self.playButton.selected = YES;
            self.playButton.hidden = NO;
        }];
        

    }];
    // 停滞不前
    [[LLNotifyCenter shareCenter] addObserver:self name:AVPlayerItemPlaybackStalledNotification object:nil usingBlock:^(NSNotification * _Nullable notify) {
        @strongify(self)
        [self.activityView startAnimating];
    }];
    //停止播放
    [[LLNotifyCenter shareCenter] addObserver:self name:AVPlayerItemPlaybackStalledNotification object:nil usingBlock:^(NSNotification * _Nullable notify) {
        NSLog(@"停止播放");
    }];
    //播放失败
    [[LLNotifyCenter shareCenter] addObserver:self name:AVPlayerItemFailedToPlayToEndTimeNotification object:nil usingBlock:^(NSNotification * _Nullable notify) {
        NSLog(@"播放失败");
    }];
    //进入后台
    [[LLNotifyCenter shareCenter] addObserver:self name:UIApplicationWillResignActiveNotification object:nil usingBlock:^(NSNotification * _Nullable notify) {
        @strongify(self)
        [self.avPlayer pause];
    }];
    
    // 返回前台
    [[LLNotifyCenter shareCenter] addObserver:self name:UIApplicationDidBecomeActiveNotification object:nil usingBlock:^(NSNotification * _Nullable notify) {
        [self.avPlayer play];
    }];
    
    
}

//配置观察者
- (void)configObserver
{
    //播放状态
    [self.avPlayer.currentItem addObserver:self forKeyPath:@"status" options:NSKeyValueObservingOptionNew context:nil];
    //缓冲进度
    [self.avPlayer.currentItem addObserver:self forKeyPath:@"loadedTimeRanges" options:NSKeyValueObservingOptionNew context:nil];
    [self.fullScreenButton addObserver:self forKeyPath:@"selected" options:NSKeyValueObservingOptionNew context:nil];
    [self.topOperationView addObserver:self forKeyPath:@"alpha" options:NSKeyValueObservingOptionNew context:nil];
    self.needRemoveObserver = YES;
    // 视频播放时设置进度条
    @weakify(self)
    [self.avPlayer addPeriodicTimeObserverForInterval:CMTimeMake(1.0, 1.0) queue:dispatch_get_main_queue() usingBlock:^(CMTime time) {
        @strongify(self)
        AVPlayerItem *playerItem = self.avPlayer.currentItem;
        //获取当前播放到了多少秒
        self.currentPlaySecondTime = (NSInteger)CMTimeGetSeconds(time);
        //获取全部资源大小
        CGFloat total = CMTimeGetSeconds([playerItem duration]);
        //计算进度
        if (self.currentPlaySecondTime && !self.isDragingSlider) {
            // 拖动滑块的过程中不设置进度
            [self.progressSlider setValue:(self.currentPlaySecondTime / total) animated:YES];
            [self setTimeLabelTextWithLabel:self.playTimeLabel CurrentOrTotalTime:self.currentPlaySecondTime];
            
            self.bottomProgressView.progress = self.currentPlaySecondTime / total;
        }
        
    }];
    
}

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
    if ([keyPath isEqualToString:@"status"]) {
        AVPlayerItemStatus playerItemStatus = [change[NSKeyValueChangeNewKey] integerValue];
        if (playerItemStatus == AVPlayerItemStatusReadyToPlay) {
            //准备播放
            CMTime totalTime = self.avPlayer.currentItem.duration;
            CGFloat totalTimeSeconds = (CGFloat)totalTime.value / totalTime.timescale;
            NSLog(@"正在播放...，视频总长度:%.2f", totalTimeSeconds);
            self.totalTime = totalTimeSeconds;
            self.progressSetView.totalSecond = totalTimeSeconds;
            //设置总时间
            [self setTimeLabelTextWithLabel:self.totalTimeLabel CurrentOrTotalTime:totalTimeSeconds];
        }
        
    } else if ([keyPath isEqualToString:@"loadedTimeRanges"]) {
        
        NSArray *array = self.avPlayer.currentItem.loadedTimeRanges;
        //缓冲时间范围
        CMTimeRange timeRange = [array.lastObject CMTimeRangeValue];
        CGFloat startSeconds = CMTimeGetSeconds(timeRange.start);
        CGFloat durationSeconds = CMTimeGetSeconds(timeRange.duration);
        NSTimeInterval totalBufferTime = startSeconds + durationSeconds;
        //设置缓冲进度
        if (self.totalTime > 0) {
            [self.progressView setProgress:totalBufferTime / self.totalTime animated:YES];
        }
        
    } else if ([keyPath isEqualToString:@"selected"]) {
        ScreenStatus screenStatus = self.fullScreenButton.selected ? LandscapePlayStatus : VerticalPlayStatus;
        if (self.screenStatusBlock) {
            self.screenStatusBlock(screenStatus);
        }
    } else if ([keyPath isEqualToString:@"alpha"]) {
        if (self.operationViewIsHiddenBlock) {
            self.operationViewIsHiddenBlock(self.topOperationView.alpha == 0);
        }
    }
}

//设置显示时间
- (void)setTimeLabelTextWithLabel:(UILabel *)label CurrentOrTotalTime:(CGFloat)time
{
    NSDate *d = [NSDate dateWithTimeIntervalSince1970:time];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    if (time/3600 >=1) {
        [formatter setDateFormat:@"HH:mm:ss"];
    }else{
        [formatter setDateFormat:@"00:mm:ss"];
    }
    NSString * showTimeNew = [formatter stringFromDate:d];
    label.text = showTimeNew;
}

/// 拖动滑块中
- (void)progressSliderAction:(UISlider *)slider
{
    [self showOperationView];
    ///取消自动隐藏
    [self cancelAutoHiddenOperationView];
    ///拖动滑块中
    self.isDragingSlider = YES;
    // 设置播放时长label
    CGFloat current = (CGFloat)(self.totalTime * slider.value);
    [self setTimeLabelTextWithLabel:self.playTimeLabel CurrentOrTotalTime:current];
    
    self.bottomProgressView.progress = current / self.totalTime;
}

///滑块拖动结束
- (void)progressSliderEndAction:(UISlider *)slider
{
    ///拖拽结束
    self.isDragingSlider = NO;
    [self autoHiddenOperationView];  //添加自动隐藏
    CGFloat current = (CGFloat)(self.totalTime * slider.value);
    CMTime currentTime = CMTimeMake(current, 1);
    //跳转播放
    [self.avPlayer seekToTime:currentTime completionHandler:^(BOOL finished) {
        NSLog(@"从拖动结束的位置开始播放了");
    }];
    [self.activityView startAnimating];
}

- (void)layoutSubviews
{
    [super layoutSubviews];
    
    // 上部分
    [self.topOperationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(self);
        make.height.mas_equalTo(kTopOperationViewH);
    }];
    
    CGFloat backBtn_left = _statusBarH > 20 ? _statusBarH : 0;
    [self.backButton mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.topOperationView);
        make.left.mas_equalTo(backBtn_left);
        make.height.width.equalTo(self.topOperationView.mas_height);
    }];
    MASViewAttribute *leftAttribute = self.backButton.hidden ? self.mas_left : self.backButton.mas_right;
    [self.movieName mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(leftAttribute);
        make.top.height.right.equalTo(self.topOperationView);
    }];
    
    // 下部分
    [self.bottomOperationView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self);
        make.height.mas_equalTo(kBottomOprationViewH);
    }];
    [self.fullScreenButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.right.equalTo(self.bottomOperationView);
        make.height.width.equalTo(self.bottomOperationView.mas_height);
    }];
    [self.totalTimeLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.fullScreenButton.mas_left);
        make.bottom.height.equalTo(self.bottomOperationView);
    }];
    CGFloat playTimeLabelLeft = self.backButton.hidden ? 0 : backBtn_left;
    [self.playTimeLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(playTimeLabelLeft);
        make.width.mas_equalTo(70);
        make.bottom.height.equalTo(self.bottomOperationView);
    }];
    
    // 进度条
    [self.progressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.playTimeLabel.mas_right).mas_offset(0);
        make.right.equalTo(self.totalTimeLabel.mas_left).mas_offset(-10);
        make.centerY.equalTo(self.bottomOperationView).mas_offset(1);
        make.height.mas_equalTo(2);
    }];
    [self.progressSlider mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.progressView);
        make.bottom.height.equalTo(self.bottomOperationView);
    }];
    //最下面的那个最长进度条
    [self.bottomProgressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self);
        make.height.mas_equalTo(1);
    }];
    
    // 播放按钮
    [self.playButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
    }];
    
    [self.progressSetView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
        make.width.mas_equalTo(240);
        make.height.mas_equalTo(40);
    }];
    
    ///菊花
    [self.activityView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.equalTo(self);
    }];
    
    [self.volumeOrLightProgressView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self).mas_offset(20);
        make.centerX.equalTo(self);
        make.width.mas_equalTo(160);
        make.height.mas_equalTo(2);
    }];
    
    [self.volumeOrLightImageView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.volumeOrLightProgressView.mas_left).mas_offset(-5);
        make.centerY.equalTo(self.volumeOrLightProgressView);
    }];
    
    // 播放器layer
    [self layoutIfNeeded];
    self.playerLayer.frame = self.bounds;
    
}

/// 播放按钮
- (void)playButtonClick:(UIButton *)sender
{
    sender.selected = !sender.selected;
    sender.selected ? [self.avPlayer pause] : [self.avPlayer play];
}

/// 全屏 半屏按钮
- (void)fullScreenButtonClick:(UIButton *)sender
{
    sender.selected = !sender.selected;
    self.backButton.hidden = !sender.selected;
    if (sender.selected) {
        [self setInterfaceOrientation:UIInterfaceOrientationLandscapeRight];
//        self.frame = self.viewController.view.bounds;
        self.frame = [UIApplication sharedApplication].keyWindow.bounds;
        
        [self addSelfToWindow];
        
    } else {
        [self setInterfaceOrientation:UIInterfaceOrientationPortrait];
        self.frame = self.originFrame;
        
        [self addSelfToMyOriginSuperView];
    }
    
    
}

///返回按钮点击了
- (void)backButtonAction:(UIButton *)sender
{
    sender.hidden = YES;
    self.fullScreenButton.selected = NO;
    
    [self setInterfaceOrientation:UIInterfaceOrientationPortrait];
    self.frame = self.originFrame;
    
   
    [self addSelfToMyOriginSuperView];
    
    
}

//上部操作视图
- (UIView *)topOperationView
{
    if (!_topOperationView) {
        _topOperationView = [[UIView alloc] init];
//        _topOperationView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.3];
        [self addSubview:_topOperationView];
    }
    return _topOperationView;
}

- (UIButton *)backButton
{
    if (!_backButton) {
        _backButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_backButton setImage:[UIImage imageNamed:@"ll_back"] forState:UIControlStateNormal];
        _backButton.imageView.contentMode = UIViewContentModeCenter;
        [_backButton addTarget:self action:@selector(backButtonAction:) forControlEvents:UIControlEventTouchUpInside];
        _backButton.hidden = YES;
        [self.topOperationView addSubview:_backButton];
    }
    return _backButton;
}

- (UILabel *)movieName
{
    if (!_movieName) {
        _movieName = [[UILabel alloc] init];
//        _movieName.text = @"";
        _movieName.textColor = [UIColor whiteColor];
        [self.topOperationView addSubview:_movieName];
    }
    return _movieName;
}

//下部操作视图
- (UIView *)bottomOperationView
{
    if (!_bottomOperationView) {
        _bottomOperationView = [[UIView alloc] init];
//        _bottomOperationView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.3];
        [self addSubview:_bottomOperationView];
    }
    return _bottomOperationView;
}

- (UIButton *)playButton
{
    if (!_playButton) {
        _playButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_playButton setImage:[UIImage imageNamed:@"ll_pause"] forState:UIControlStateNormal];
        [_playButton setImage:[UIImage imageNamed:@"ll_play"] forState:UIControlStateSelected];
        _playButton.imageView.contentMode = UIViewContentModeCenter;
        [_playButton addTarget:self action:@selector(playButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self addSubview:_playButton];
    }
    return _playButton;
}

- (UILabel *)playTimeLabel
{
    if (!_playTimeLabel) {
        _playTimeLabel = [[UILabel alloc] init];
        _playTimeLabel.text = @"00:00:00";
        _playTimeLabel.textColor = [UIColor whiteColor];
        _playTimeLabel.font = [UIFont systemFontOfSize:12];
        _playTimeLabel.textAlignment = NSTextAlignmentCenter;
        [self.bottomOperationView addSubview:_playTimeLabel];
    }
    return _playTimeLabel;
}

- (UILabel *)totalTimeLabel
{
    if (!_totalTimeLabel) {
        _totalTimeLabel = [[UILabel alloc] init];
        _totalTimeLabel.text = @"00:00:00";
        _totalTimeLabel.textColor = [UIColor whiteColor];
        _totalTimeLabel.font = [UIFont systemFontOfSize:12];
        [self.bottomOperationView addSubview:_totalTimeLabel];
    }
    return _totalTimeLabel;
}

///缓冲进度条
- (UIProgressView *)progressView
{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] init];
        _progressView.progress = 0.0f;
        _progressView.progressTintColor = [UIColor whiteColor];
        _progressView.trackTintColor = [UIColor grayColor];
        [self.bottomOperationView addSubview:_progressView];
    }
    return _progressView;
}

- (UISlider *)progressSlider
{
    if (!_progressSlider) {
        _progressSlider = [[UISlider alloc] initWithFrame:self.progressView.frame];
        _progressSlider.value = 0.0f;
        [_progressSlider setThumbImage:[UIImage imageNamed:@"ll_dot"] forState:UIControlStateNormal];
        _progressSlider.minimumTrackTintColor = [UIColor redColor];
        _progressSlider.maximumTrackTintColor = [UIColor clearColor];
        [_progressSlider addTarget:self action:@selector(progressSliderAction:) forControlEvents:UIControlEventValueChanged];
        [_progressSlider addTarget:self action:@selector(progressSliderEndAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomOperationView addSubview:_progressSlider];
    }
    return _progressSlider;
}

- (UIProgressView *)bottomProgressView
{
    if (!_bottomProgressView) {
        _bottomProgressView = [[UIProgressView alloc] init];
        _bottomProgressView.progress = 0.0f;
        _bottomProgressView.progressTintColor = [UIColor redColor];
        _bottomProgressView.trackTintColor = [UIColor clearColor];
        [self addSubview:_bottomProgressView];
    }
    return _bottomProgressView;
}

- (UIButton *)fullScreenButton
{
    if (!_fullScreenButton) {
        _fullScreenButton = [UIButton buttonWithType:UIButtonTypeCustom];
        [_fullScreenButton setImage:[UIImage imageNamed:@"ll_full"] forState:UIControlStateNormal];
        [_fullScreenButton setImage:[UIImage imageNamed:@"ll_half"] forState:UIControlStateSelected];
        _fullScreenButton.imageView.contentMode = UIViewContentModeCenter;
        [_fullScreenButton addTarget:self action:@selector(fullScreenButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [self.bottomOperationView addSubview:_fullScreenButton];
    }
    return _fullScreenButton;
}

- (AVPlayerLayer *)playerLayer
{
    if (!_playerLayer) {
        _playerLayer = [AVPlayerLayer playerLayerWithPlayer:nil];
        // 填充模式
//        _playerLayer.videoGravity = AVLayerVideoGravityResizeAspect;
        [self.layer insertSublayer:_playerLayer atIndex:0];
    }
    return _playerLayer;
}

- (LLProgressSetView *)progressSetView
{
    if (!_progressSetView) {
        _progressSetView = [[LLProgressSetView alloc] init];
        _progressSetView.hidden = YES;
        [self addSubview:_progressSetView];
    }
    return _progressSetView;
}

- (UIProgressView *)volumeOrLightProgressView
{
    if (!_volumeOrLightProgressView) {
        _volumeOrLightProgressView = [[UIProgressView alloc] init];
        _volumeOrLightProgressView.progressTintColor = [UIColor whiteColor];
        _volumeOrLightProgressView.trackTintColor = [UIColor grayColor];
        [self addSubview:_volumeOrLightProgressView];
    }
    return _volumeOrLightProgressView;
}

- (UIImageView *)volumeOrLightImageView
{
    if (!_volumeOrLightImageView) {
        _volumeOrLightImageView = [[UIImageView alloc] init];
        [self addSubview:_volumeOrLightImageView];
    }
    return _volumeOrLightImageView;
}

- (UIActivityIndicatorView *)activityView
{
    if (!_activityView) {
        _activityView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhite];
        [self addSubview:_activityView];
    }
    return _activityView;
}

//屏幕平移手势
- (void)addPanGestureRecognizer
{
    if (self.moviePan == nil) {
        self.moviePan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(moviePanAction:)];
        [self addGestureRecognizer:self.moviePan];
    }
}

//移除平移手势
- (void)removePanGestureRecognizer
{
    [self removeGestureRecognizer:self.moviePan];
    self.moviePan = nil;
}


//取消调用自动隐藏的方法
- (void)cancelAutoHiddenOperationView
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(hiddenOperationView) object:nil];
}

//添加自动隐藏
- (void)autoHiddenOperationView
{
    [self performSelector:@selector(hiddenOperationView) withObject:nil afterDelay:kTimerDuration];
}

- (void)showOperationView
{
    self.topAndBottomHidden = NO;
    self.playButton.hidden = NO;
    
    [UIView animateWithDuration:0.3 animations:^{
        self.topOperationView.alpha = 1;
        self.bottomOperationView.alpha = 1;
        
        self.bottomProgressView.alpha = 0;
    }];
}

//隐藏上下操作视图
- (void)hiddenOperationView
{
    self.topAndBottomHidden = YES;
    self.playButton.hidden = YES;
    
    [UIView animateWithDuration:0.3 animations:^{
        self.topOperationView.alpha = 0;
        self.bottomOperationView.alpha = 0;
        
        self.bottomProgressView.alpha = 1;
        
    }];
}
///处理屏幕旋转
- (void)handleScreenRotation
{
    @weakify(self)
    [self.viewController aspect_hookSelector:@selector(viewWillTransitionToSize:withTransitionCoordinator:) withOptions:AspectPositionInstead usingBlock:^(id<AspectInfo> info, CGSize size, id<UIViewControllerTransitionCoordinator> coordinator){
        @strongify(self)
        ///动画时长，动画结束之后获取设备旋转方向
        @weakify(self)
        NSTimeInterval interval = [coordinator transitionDuration];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(interval * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            @strongify(self)
            UIInterfaceOrientation orientation = [UIApplication sharedApplication].statusBarOrientation;
            
            if (orientation == UIInterfaceOrientationPortrait) {
                // 竖向
                self.fullScreenButton.selected = NO;
                self.frame = self.originFrame;
                self.backButton.hidden = YES;
                
                [self addSelfToMyOriginSuperView];
                
            } else if (orientation == UIInterfaceOrientationLandscapeLeft || orientation == UIInterfaceOrientationLandscapeRight) {
                self.fullScreenButton.selected = YES;
                self.frame = self.viewController.view.bounds;
                self.backButton.hidden = NO;
                
                [self addSelfToWindow];
            }
            
        });
    } error:nil];
}

//强制转屏（这个方法最好放在BaseVController中）
- (void)setInterfaceOrientation:(UIInterfaceOrientation)orientation{
    if ([[UIDevice currentDevice] respondsToSelector:@selector(setOrientation:)]) {
        SEL selector  = NSSelectorFromString(@"setOrientation:");
        NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:[UIDevice instanceMethodSignatureForSelector:selector]];
        [invocation setSelector:selector];
        [invocation setTarget:[UIDevice currentDevice]];
        // 从2开始是因为前两个参数已经被selector和target占用
        [invocation setArgument:&orientation atIndex:2];
        [invocation invoke];
    }
}

- (void)addSelfToMyOriginSuperView
{
    // 移除pan手势滑动事件
    [self removePanGestureRecognizer];
    
    [self removeFromSuperview];
    if (![self.mySuperView.subviews containsObject:self]) {
        [self.mySuperView addSubview:self];
    }
    
    [self setNeedsLayout];
}

- (void)addSelfToWindow
{
    // 添加pan手势滑动事件
    [self addPanGestureRecognizer];
    ///添加到window上
    [self removeFromSuperview];
    if (![[UIApplication sharedApplication].keyWindow.subviews containsObject:self]) {
        [[UIApplication sharedApplication].keyWindow addSubview:self];
    }
    
    [self setNeedsLayout];
}


- (MPVolumeView *)volumeView
{
    if (!_volumeView) {
        _volumeView = [[MPVolumeView alloc] init];
        _volumeView.backgroundColor = [UIColor cyanColor];
        _volumeView.showsVolumeSlider = NO;
        _volumeView.showsRouteButton = NO;
        [self addSubview:_volumeView];
    }
    return _volumeView;
}

- (UISlider *)volumeViewSlider
{
    if (!_volumeViewSlider) {
        for(UIView *view in self.volumeView.subviews) {
            if ([view.class.description isEqualToString:@"MPVolumeSlider"]){
                _volumeViewSlider = (UISlider*)view;
                _volumeViewSlider.minimumTrackTintColor = [UIColor redColor];
                _volumeViewSlider.maximumTrackTintColor = [UIColor blackColor];
                break;
            }
        }
    }
    
    return _volumeViewSlider;
}


///移除观察者
- (void)remoAllOberver
{
    [self pause];
    [[LLNotifyCenter shareCenter] removeObserver:self];
    if (self.needRemoveObserver) {
        [self.avPlayer.currentItem removeObserver:self forKeyPath:@"status"];
        [self.avPlayer.currentItem removeObserver:self forKeyPath:@"loadedTimeRanges"];
        [self.fullScreenButton removeObserver:self forKeyPath:@"selected"];
        [self.topOperationView removeObserver:self forKeyPath:@"alpha"];
        self.needRemoveObserver = NO;
    }
    
}

- (void)dealloc
{
    NSLog(@"移除了");
}



@end
